﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcTestApp.Utility;
using MvcTestApp.Models;
using System.Data;
using System.Reflection;

namespace MvcTestApp.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            GetModelProperties(new RegisterModel().GetType());
            DataTable dt = BuildDataTable();
            DateTime start = DateTime.Now;
            ListConfig config = ParsingEngine.BuildConfiguration("Group Name{ ID | Name | Password  }, Personal Info{Email}, Picture{Image:<img src='/ProductImages/{0}' alt='{1}' title='{2}' />(ThumbImage ~ ID ~ Name) }, Description{Description}",
                dt, true, "/Product/Edit/{0}");
            DateTime end = DateTime.Now;
            TimeSpan span = end.Subtract(start);
            String elapsedTime = span.TotalMilliseconds.ToString();
            ViewBag.Message = "Welcome to LightBox App!";

            String sessionID = Session.SessionID;
            //HttpContext.Session["asdsd"] = "This Is A Fundamental Test";
            SessionCache.CurrentUser = "This is a test User";

            List<RegisterModel> items = new List<RegisterModel>();
            SelectList list = SessionCache.GetSelectList<RegisterModel>(items, "UserName", "Email");
            ViewBag.ListConfig = config;            
            return View();
        }

        public ActionResult TestPage()
        {
            return View();
        }
        [HttpPost]
        public String AjaxGetServerTime(String userId)
        {
            int id = Convert.ToInt32(userId);
            return String.Format("Given Value Is: {0}", id);
        }
        private DataTable BuildDataTable()
        {
            DataTable dt = new DataTable();
            //dt.Columns = new DataColumnCollection();
            dt.Columns.Add("ID");
            dt.Columns.Add("Name");
            dt.Columns.Add("Email");
            dt.Columns.Add("Password");
            dt.Columns.Add("ThumbImage");
            dt.Columns.Add("Description");

            for (int i = 1; i < 6; i++)
            {
                DataRow row = dt.NewRow();
                row["ID"] = i;
                row["Name"] = String.Format("Hassanur_{0}", i);
                row["Password"] = System.Guid.NewGuid().ToString();
                row["Email"] = String.Format("myemail{0}@gmail.com", i);
                row["ThumbImage"] = String.Format("thumb-{0}.jpg", i);
                row["Description"] = String.Format("This is description text ({0})", i);
                dt.Rows.Add(row);
            }
            return dt;
        }

        public ActionResult About()
        {            
            return View();
        }

        public ActionResult LightBox()
        {
            return View();
        }
        
        [HttpPost]
        public String AjaxTest(String name)
        {
            return String.Format("Your Name is {0} at {1}", name, DateTime.Now.ToString("MMMM dd, yyyy hh:mm tt"));
        }
        public ActionResult jQueryModal()
        {
            return View();
        }

        public void TestMethod()
        {
            
        }

        public List<ModelProperty> GetModelProperties(Type type)
        {
            List<ModelProperty> results = GetEligibleProperties(type);

            foreach (ModelProperty prop in results)
            {
                if (prop.UnderlyingType == typeof(double) || prop.UnderlyingType == typeof(decimal))
                {
                    prop.ValueExpression = "String.Format(\"{0:F}\", " + prop.ValueExpression + ")";
                }
                else if (prop.UnderlyingType == typeof(DateTime))
                {
                    prop.ValueExpression = "String.Format(\"{0:g}\", " + prop.ValueExpression + ")";
                }
            }

            return results;
        }

        List<ModelProperty> GetEligibleProperties(Type type)
        {
            List<ModelProperty> results = new List<ModelProperty>();

            foreach (PropertyInfo prop in type.GetProperties(BindingFlags.Public | BindingFlags.Instance))
            {   
                Type underlyingType = Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType;
                if (prop.GetGetMethod() != null && prop.GetIndexParameters().Length == 0)// && IsBindableType(underlyingType))
                {
                    if (Attribute.IsDefined(prop, typeof(System.ComponentModel.DataAnnotations.DataTypeAttribute)))
                    {
                        Console.WriteLine("Found DataType attribute.");
                    }
                    String attributeName = prop.Attributes.ToString();                    
                    
                    results.Add(new ModelProperty
                    {
                        Name = prop.Name,
                        ValueExpression = "Model." + prop.Name,
                        UnderlyingType = underlyingType,
                        //IsPrimaryKey = IsPrimaryKey(prop),
                        IsReadOnly = prop.GetSetMethod() == null
                    });
                }
            }

            return results;
        }
    }

    public class ModelProperty
    {
        public string Name { get; set; }
        public string ValueExpression { get; set; }
        public Type UnderlyingType { get; set; }
        public bool IsPrimaryKey { get; set; }
        public bool IsReadOnly { get; set; }
    }
}
